package kr.or.javacafe.extra.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.xml.MarshallingView;


import kr.or.common.util.PagingHelper;
import kr.or.common.util.RoleUtil;
import kr.or.javacafe.board.bo.BoardBO;
import kr.or.javacafe.board.domain.Article;
import kr.or.javacafe.board.domain.Bbs;
import kr.or.javacafe.code.bo.CodeCategoryBO;
import kr.or.javacafe.manage.bo.*;
import kr.or.javacafe.manage.domain.*;
import kr.or.javacafe.member.bo.MemberBO;
import kr.or.javacafe.member.domain.User;
import kr.or.javacafe.member.domain.UserTeam;

@Controller
@RequestMapping("/extra")
public class ExtraController {
	
	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(ExtraController.class);
		
	@Value("#{commonProp['board.paging.row.range']}")
	int m_intRowRange; // 한페이지에 보여줄 레코드 수

	@Value("#{commonProp['board.paging.page.range']}")
	int m_intPageRange; // 페이징한 블럭 갯수

	@Value("#{commonProp['board.article.file.path.server.temp']}")
	String m_strServerUploadPathTemp; 

	@Value("#{commonProp['board.article.file.path.server.real']}")
	String m_strServerUploadPathReal; 

	@Value("#{commonProp['board.article.file.path.local.temp']}")
	String m_strLocalUploadPathTemp; 

	@Value("#{commonProp['board.article.file.path.local.real']}")
	String m_strLocalUploadPathReal; 

	String m_SEPARATOR = System.getProperty("file.separator");

	@Autowired
	CodeCategoryBO codeCategoryBO;
	
	@Autowired
	ManageBO manageBO;
	
	@Autowired
	MemberBO memberBO;
	
	@Autowired
	BoardBO boardBO;

	

	@RequestMapping(value = "/json/welcome", method = RequestMethod.GET)
	@ResponseBody
	public Information jsonWelcomeText() {
		return manageBO.getWelcome();
	}

	@RequestMapping(value = "/xml/welcome", method = RequestMethod.GET)
	public void xmlWelcomeText(HttpServletResponse response) throws IOException {
		Information objData =  manageBO.getWelcome();
				
		String strHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		String strContents = "<info>";
		strContents += "<id>" + objData.getId() + "</id>";
		strContents += "<editUserId>" + objData.getEditUserId() + "</editUserId>";
		strContents += "<editDate>" + objData.getEditDate() + "</editDate>";
		strContents += "<contents><![CDATA[" + objData.getContents() + "]]></contents>";
		strContents += "</info>";
			
		response.setContentType("application/xml; charset=utf-8");
		response.getWriter().append(strHeader + strContents);
	}

	@RequestMapping(value = "/xml/history", method = RequestMethod.GET)
	public void xmlHistoryText(HttpServletResponse response) throws IOException {
		Information objData =  manageBO.getHistory();
				
		String strHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		String strContents = "<info>";
		strContents += "<id>" + objData.getId() + "</id>";
		strContents += "<editUserId>" + objData.getEditUserId() + "</editUserId>";
		strContents += "<editDate>" + objData.getEditDate() + "</editDate>";
		strContents += "<contents><![CDATA[" + objData.getContents() + "]]></contents>";
		strContents += "</info>";
			
		response.setContentType("application/xml; charset=utf-8");
		response.getWriter().append(strHeader + strContents);
	}

	@RequestMapping(value = "/xml/regulation", method = RequestMethod.GET)
	public void xmlRegulationText(HttpServletResponse response) throws IOException {
		Information objData =  manageBO.getRegulation();
				
		String strHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		String strContents = "<info>";
		strContents += "<id>" + objData.getId() + "</id>";
		strContents += "<editUserId>" + objData.getEditUserId() + "</editUserId>";
		strContents += "<editDate>" + objData.getEditDate() + "</editDate>";
		strContents += "<contents><![CDATA[" + objData.getContents() + "]]></contents>";
		strContents += "</info>";
			
		response.setContentType("application/xml; charset=utf-8");
		response.getWriter().append(strHeader + strContents);
	}


	
	
	
	@RequestMapping(value = "/json/BBS_ID/{bbsId}", method = RequestMethod.GET)
	@ResponseBody
	public Map jsonBoardList(@RequestParam(value = "single", required = false, defaultValue = "") String single, String page, @PathVariable String bbsId, HttpServletRequest request, Model model) {
		
		// 게시판 관리 정보
		Bbs objBbsInfo = boardBO.getBbsInfo(bbsId);
		
		// 게시판 권한 정보
		String strRoleRead = "";
		String strRoleWrite = "";		
		User objUserInfo = RoleUtil.getUserInfo();
		if (objUserInfo == null) {
			strRoleRead = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "R", "G0");
			strRoleWrite = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "W", "G0");
		} else {
			strRoleRead = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "R", objUserInfo.getRoleGrpId());
			strRoleWrite = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "W", objUserInfo.getRoleGrpId());
		}			
		// 목록 조회시 [읽기권한]이 없는 경우 로그인 페이지로 이동시킨다.
		if (strRoleRead == "") throw new UsernameNotFoundException("목록 조회시 접근한 게시판에 Read 권한이 존재하지않습니다.");


		// 게시판 정보
		Article article = new Article();
		article.setBbsId(bbsId);

		// Page 정보
		if (page == null) page = "1";
		if (page.equals("")) page = "1";

		int totalRows = boardBO.getListArticleCount(article);
		int rowRange = m_intRowRange;
		int pageRange = m_intPageRange;
		int pageNum = Integer.parseInt(page);
		String pageURL = "/board/list/BBS_ID/" + bbsId;

		PagingHelper pHelper = PagingHelper.instance;
		pHelper.init(totalRows, rowRange, pageRange, pageNum);

		String pageHTML = pHelper.getPagingHTML(single, pageURL);

		int startNum = pHelper.getStartRownum();
		int endNum = pHelper.getEndRownum();

		article.setStartBbsThread(startNum);
		article.setEndBbsThread(endNum);
		List<Article> objArticleList = boardBO.listArticle(article);

		Map objMap = new HashMap();

		objMap.put("boardRoleRead", strRoleRead);
		objMap.put("boardRoleWrite", strRoleWrite);
		objMap.put("single", single);
		
		objMap.put("objBbsInfo", objBbsInfo);
		objMap.put("objArticleList", objArticleList);
		objMap.put("pageHTML", pageHTML);
		objMap.put("page", page);
		
		if (!objBbsInfo.getCdCatId().equals("")) {
			// 게시판 카테고리 정보가 존재할 경우 카테고리 정보를 보여준다.
			objMap.put("boardCatgList", codeCategoryBO.listCodeCategoryForCombo(objBbsInfo.getCdCatId()));			
		}
			
		return objMap;
	}	
	
	
	@RequestMapping(value = "/json/BBS_ID/{bbsId}/ATC_NO/{atcNo}", method = RequestMethod.GET)
	@ResponseBody
	public Map jsonBoardView(@RequestParam(value = "single", required = false, defaultValue = "") String single, String page, @PathVariable String bbsId, @PathVariable String atcNo, HttpServletRequest request, Model model) {

		// 게시판 관리 정보
		Bbs objBbsInfo = boardBO.getBbsInfo(bbsId);

		// 게시판 권한 정보
		String strRoleRead = "";
		String strRoleWrite = "";		
		User objUserInfo = RoleUtil.getUserInfo();
		if (objUserInfo == null) {
			strRoleRead = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "R", "G0");
			strRoleWrite = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "W", "G0");
		} else {
			strRoleRead = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "R", objUserInfo.getRoleGrpId());
			strRoleWrite = RoleUtil.getRoleByBoardRead(objBbsInfo.getBbsRole(), "W", objUserInfo.getRoleGrpId());
		}			
		// 내용 조회시 [읽기권한]이 없는 경우 로그인 페이지로 이동시킨다.
		if (strRoleRead == "") throw new UsernameNotFoundException("내용 조회시 접근한 게시판에 Read 권한이 존재하지않습니다.");


		// 게시판 정보
		Article article = new Article();
		article.setBbsId(bbsId);

		// Page 정보
		if (page == null) page = "1";
		if (page.equals("")) page = "1";
 
		int totalRows = boardBO.getListArticleCount(article);
		int rowRange = m_intRowRange;
		int pageRange = m_intPageRange;
		int pageNum = Integer.parseInt(page);
		String pageURL = "/board/list/BBS_ID/" + bbsId;

		PagingHelper pHelper = PagingHelper.instance;
		pHelper.init(totalRows, rowRange, pageRange, pageNum);

		String pageHTML = pHelper.getPagingHTML(single, pageURL);
		
		int startNum = pHelper.getStartRownum();
		int endNum = pHelper.getEndRownum();

		Article objViewArticle = null;

		article.setStartBbsThread(startNum);
		article.setEndBbsThread(endNum);
		List<Article> objArticleList = boardBO.listArticle(article);

		// 사용자 정보
		String strId = "";
		if (objUserInfo != null) strId = objUserInfo.getId();
		
		// 권한정보
		String strAuth = "";
		if (objUserInfo != null) {
			strAuth = objUserInfo.getRoleGrpId();
		}
		
		Map objMap = new HashMap();
		
		objMap.put("userRole", strAuth);
		objMap.put("boardRoleRead", strRoleRead);
		objMap.put("boardRoleWrite", strRoleWrite);
		objMap.put("single", single);
		
		objMap.put("objBbsInfo", objBbsInfo);
		objMap.put("objArticleList", objArticleList);
		objMap.put("pageHTML", pageHTML);
		objMap.put("page", page);
		objMap.put("objViewArticle", objViewArticle);
		objMap.put("userId", strId);

		if (!objBbsInfo.getCdCatId().equals("")) {
			// 게시판 카테고리 정보가 존재할 경우 카테고리 정보를 보여준다.
			objMap.put("boardCatgList", codeCategoryBO.listCodeCategoryForCombo(objBbsInfo.getCdCatId()));			
		}
		
		return objMap;
	}
	
	
}






